//
//  UserAccountViewModel.swift
//  01- 搭建框架
//
//  Created by as888 on 15/10/17.
//  Copyright © 2015年 任伟. All rights reserved.
//

import Foundation

/// MARK: -用户账户视图模型
class UserAccountViewModel {
    
    //增加单例的静态常量
    static let sharedUserAccount = UserAccountViewModel()
    
    //判断用户登录标记
    var userLogon: Bool {
        
        return account?.access_token != nil && !isExpired
    }
    
    // 返回有效的 token
    /// token 字典
    var tokenDict: [String: AnyObject]? {
        return isExpired ? nil : ["access_token": account!.access_token!]
    }

    //用户账户
    var account: UserAccount?
    
    /// 判断用户是否过期（增加过期处理计算型属性）
    private var isExpired: Bool {
    
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // 代码执行到此，一定进行过比较！
            return false
        }
        
        return true
    }
    
    //头像 url
    var avatarUrl: NSURL {
        return NSURL(string: account?.avatar_large ?? "")!
    }
    
    /// 归档路径
    private var accountPath: String{
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
        
    }
    
    /// MARK: -构造函数
    private init() {
    
        //从沙盒加载用户的信息
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath)
as? UserAccount
        
        //如果账号已经过期，清空账号，要求用户重新登录
        if isExpired {
        
            print("已经过期")
            account = nil
        }
    
    }
}

/// MARK: - 网络业务漏极
extension UserAccountViewModel {

    ///加载 AccessToken
    func loadAccessToke(code: String, fininsed: (isSuccessed: Bool)->()) {
        //4. 加载 accessToken(网络请求的方法)
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            // 1> 判断错误
            if error != nil {
                fininsed(isSuccessed: false)
                return
            }
            
            // 2> 记录用户的属性
           self.account = UserAccount(dict: result as! [String: AnyObject])
            
            // 3> 加载用户信息
            self.loadUserInfo(self.account!, fininsed:fininsed)
        }
    }
    
    ///加载用户的信息
    private func loadUserInfo(account: UserAccount, fininsed: (isSuccessed: Bool)->()) {
        
        NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            
            // 判断
            if error != nil {
                
                print("加载用户出错了")
                
                return
            }
            
            
            //判断并输出具体的值
            guard let dict = result as? [String: AnyObject] else{
                
                print("格式错误")
                
                return
            }
            //保存用户信息
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            //保存对象
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            //完成回调
            fininsed(isSuccessed: true)
        }
    }
}